<?php
// =============
// This code is used to :
// 1 Fetch the content from the remote uwa_generic.php page with the params
// 2 replace the css and js external links to Yahoo's 
// =============
// needs : 
// 1 memcahce php extension 
// 2 curl php extension 
// =============
/**
 * @author rainx <jingxu@alibaba-inc.com>
 */ 


define ("YFUWA_FETCH_TIMEOUT", 20); // in seconds
define ("YFUWA_FETCH_BASE_URL", "http://nvmodules2.netvibes.com/api/uwa/frame/uwa_generic.php"); // netvibes上的uwa_generic.php页面
define("YFUWA_CACHE_SERVERS", "localhost"); // 用 | 分割的多台memcached服务器

// main start
// =============================================================
$query_string = getenv("QUERY_STRING");
$url = YFUWA_FETCH_BASE_URL . "?" . $query_string;
$url_md5 = md5($url);
$key = "yfuwa_" . $url_md5;

$memcache = new Memcache;

foreach (explode("|", YFUWA_CACHE_SERVERS) as $cache_server)
{
    // $ret = $memcache->connect('localhost', 11211);
    $ret = $memcache->addServer($cache_server , 11211);
    // error_log( $cache_server );
    if (!$ret)
    {
        // do some error process
        die();
    }
}

$content = "";

if (! ($content = $memcache->get($key)))
{
    $content = get($url);
    $memcache->set($key, $content, false, 3600 * 24); // cache 一天的时间
}

if (! empty( $content )) 
{
    // 对内容进行替换
    $content = str_replace('http://cdn.netvibes.com/themes/uwa/iframe.css', 'http://cn.yimg.com/uwacache/themes/base/uwa-iframe.css', $content);
    $content = str_replace('http://www.netvibes.com/js/UWA/load.js.php?type=Frame&env=UWA_Generic', 'http://cn.yimg.com/uwacache/js/UWA/load.js', $content);
    
    echo $content;
}
else
{
    // 错误处理
    die();
}

// =================================================
// main end

// Useful functons used in this page:
// =================================================
    /// 获取单个页面的内容和状态 (GET)
    /**
     * @param $url 你需要get页面的url
     * @returns array 返回一个数组，第一个元素是返回的header状态，第二个是抓取网页正文的内容
     */
    function get($url, $timeout=null)
    {
        if ($timeout == null)
        {
            $timeout = 5 ;
        }

        $ch = curl_init();
        if(!$ch) {
            return null;
        }
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);
        $data = curl_exec($ch);
        $status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $data;
    }


?>
